package com.smartcommunity.job;

import com.smartcommunity.api.engine.EngineApi;
import com.smartcommunity.bean.constant.Constant;
import com.smartcommunity.bean.model.Result;
import com.smartcommunity.es.common.EsBasedataEnum;
import com.smartcommunity.dao.people.PeopleDao;
import com.smartcommunity.elasticsearch.people.PeopleEsApi;
import com.smartcommunity.entity.people.People;
import com.smartcommunity.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 常住人员信息同步
 *
 * @author 渔七
 * @since 2023年1月7日
 */
@Component
@Slf4j
public class PeopleSyncJob {

    @Autowired
    private PeopleDao peopleDao;

    @Autowired
    private PeopleEsApi peopleEsApi;
    
    @Autowired
    private EngineApi engineApi;

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    /**
     * 当前任务运行状态
     */
    private boolean running;

    /**
     * 中断任务
     */
    private boolean interrupt;

    /**
     * 任务运行进度
     */
    private double processing;

    /**
     * 同步常住人员到vid引擎
     * <li>"0 0/5 2 * * *" = 2:05 AM every day.</li>
     */
    @Scheduled(initialDelay = 25*1000,fixedDelay = 30*60*1000)
    protected void syncPeople2VidEngine() {
        //如果任务多次被调用。只执行一次。
        synchronized (this) {
            if (running) {
                return;
            } else {
                running = true;
            }
        }
        log.info("同步社区实有人口到VID常口库");
        int totalCount = peopleDao.queryUnSyncPeopleCount();
        int pageSize = 1000;
        int totalPage = (totalCount / pageSize) + 1;
        int dealCount = 0;
        for (int i = 0; i < totalPage && totalCount > 0; i++) {
            if (interrupt) {
                break;
            }
            int startRow = i > 0 ? (i - 1) * pageSize : 0;
            log.info("正在同步社区实有人口到VID常口库,正在处理 {}-{} 数据", startRow, pageSize);
            List<People> unSyncPeopleList = peopleDao.queryUnSyncPeople(startRow, pageSize);
            if (!CollectionUtils.isEmpty(unSyncPeopleList)) {
            	Map<String, Map<String, Object>> esUpdateMap = new HashMap<String, Map<String,Object>>();
                for (People unSyncPeople : unSyncPeopleList) {
                    try {
                        if (interrupt) {
                            break;
                        }
                        Map<String, Object> person = new HashMap<>();
                        person.put("id", unSyncPeople.getId());
                        //此处图片并非完整地址，需要补充完整
                        if (!StringUtils.isEmpty(unSyncPeople.getIdCardPic())) {
                            person.put("pic", unSyncPeople.getIdCardPic());
                            person.put("idCard", unSyncPeople.getCredentialNo());
                            person.put("name", unSyncPeople.getPeopleName());
                            Result result = engineApi.uploadPerson(person);
                            if (result.getData() != null) {
                                Long featureId = Long.valueOf(result.getData().toString());
                                peopleDao.updateUnSyncPeople(unSyncPeople.getId(), featureId);
                                if(featureId.longValue()>0) {
	                                Map<String, Object> valueMap = new HashMap<String, Object>();
	                                valueMap.put("featureId", featureId);
	                                esUpdateMap.put(unSyncPeople.getCredentialNo()+Constant.SEPARATOR+EsBasedataEnum.PEOPLE.getIntValue(), valueMap);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("同步人员信息到VID引擎异常,人员信息：{}", unSyncPeople.toString(), e);
                    } finally {
                        dealCount++;
                        processing = ((double) dealCount) / ((double) totalCount);
                        interrupt = false;
                    }
                }
                try {
                	if(!org.springframework.util.CollectionUtils.isEmpty(esUpdateMap)) {
                		peopleEsApi.batchUpdate(esUpdateMap);
                	}
                }catch (Exception e) {
                	log.error("批量更新ES中人员特征ID失败,error:", e);
                }
            }
        }
        running = false;
    }

    //    @Scheduled(cron = "* * * * * *")
    protected void test() {

    }

    /**
     * 获取任务的运行进度
     */
    public double getProcessing() {
        return processing;
    }

    /**
     * 允许手动开启job
     */
    public void startJob() {
        if (!running) {
            threadPoolTaskScheduler.execute(this::syncPeople2VidEngine);
        }
    }

    /**
     * 允许手动停止job
     */
    public void interruptJob() {
        if (running) {
            interrupt = true;
        }
    }
}
